#!/usr/bin/env python3
"""
包名提取工具
功能：逐行分析packages_2506.txt文件，提取出包名
示例：
- agiros-loong-aandd-ekew-driver-py-0.0.2-1.oe2403.x86_64.rpm -> agiros-loong-aandd-ekew-driver-py
- agiros-loong-action-msgs-1.2.1-1.x86_64.rpm -> agiros-loong-action-msgs
"""
import re
import os

def extract_package_name(file_path):
    """
    从文件中提取包名
    参数:
        file_path: 文件路径
    返回:
        list: 提取的包名列表
    """
    package_names = []
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                
                # 去掉.rpm扩展名
                if line.endswith('.rpm'):
                    line = line[:-4]
                
                # 使用正则表达式匹配包名（按照用户要求在第一个'-数字.'前结束）
                match = re.search(r'^(.+?)-\d+\.', line)
                if match:
                    package_name = match.group(1)
                    package_names.append(package_name)
                else:
                    # 如果没有找到匹配的模式，就使用整个行（去掉.rpm后）
                    package_names.append(line)
        return package_names
    except Exception as e:
        print(f"读取文件失败: {e}")
        return []

def main():
    # 文件路径
    file_path = os.path.join(os.path.dirname(__file__), 'packages_2506.txt')
    
    # 检查文件是否存在
    if not os.path.exists(file_path):
        print(f"文件不存在: {file_path}")
        return
    
    # 提取包名
    package_names = extract_package_name(file_path)
    
    # 输出结果
    print(f"共提取到 {len(package_names)} 个包名:")
    for i, name in enumerate(package_names, 1):
        print(f"{i}. {name}")
    
    # 保存结果到文件
    output_file = os.path.join(os.path.dirname(__file__), 'extracted_package_names.txt')
    with open(output_file, 'w', encoding='utf-8') as f:
        for name in package_names:
            f.write(f"{name}\n")
    print(f"结果已保存到: {output_file}")

if __name__ == '__main__':
    main()